package com.example.kotlin.activity

import android.content.Context
import android.os.Bundle
import android.widget.Toast
import com.example.kotlin.R
import kotlinx.android.synthetic.main.activity_file_store.editToFile
import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.lang.StringBuilder

class FileStoreActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_file_store)

        val inputText = load()
        if (inputText.isNotEmpty()){
            editToFile.setText(inputText)
            editToFile.setSelection(inputText.length)
            Toast.makeText(this,"获取文件内容",Toast.LENGTH_SHORT).show()
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        val inputText = editToFile.text.toString()
        save(inputText)
    }

    private fun save(inputText: String) {
        val output = openFileOutput("data111", Context.MODE_PRIVATE)
        val write=BufferedWriter(OutputStreamWriter(output))
        write.use {
            it.write(inputText)
        }
    }

    private fun load():String{
        val content=StringBuilder()
        val input = openFileInput("data111")
        val reader = BufferedReader(InputStreamReader(input))

        reader.use { reader.forEachLine {
            content.append(it)
        } }
        return content.toString()
    }
}